package jp.co.sega.sonic_jump.monthly.sum;

import android.os.Handler;
import android.os.Looper;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import android.util.Log;
import android.content.Context;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.ByteArrayOutputStream;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class ImageDownloader {
    public String imageUrl = "https://raw.githubusercontent.com/gdgohan/SonicJumpMapEditor/main/";
    public Dates dt;
    public Bitmap bm;
    public File directory;
    public File file;

    public Bitmap getEvent(String name) {
    dt = new Dates();
    if (Game_Draw.ReadEventFile().equals("")) {
        name = name + DeviceImage.event(dt) + ".png";
        } else {
        name = name + ".png";
        }
        directory = Shell.sInstance.getExternalFilesDir(null);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        file = new File(directory, name);
        bm = getBitmapFromFile(file);
        if (bm == null) {
if (directory != null && !file.exists()) {
    for (File file : directory.listFiles()) {
        if (!file.getName().equals("Event.txt")) file.delete();
    }
}
        Bitmap downloadedBitmap = getBitmapFromURL(imageUrl + name);
        if (downloadedBitmap != null) {
            saveBitmapToAndroidData(downloadedBitmap, file);
            bm = downloadedBitmap;
        } else {
            Log.e("ImageDownloader", "Failed to download image: " + name);
        }
    }
return bm;
    }
    
    public Bitmap getBitmapFromFile(File file) {
    if (file.exists()) {
        return BitmapFactory.decodeFile(file.getAbsolutePath());
    }
    return null; // Retorna null se o arquivo não existir
}

    // Baixa a imagem e retorna como Bitmap
    public Bitmap getBitmapFromURL(String imageUrl2) {
        try {
            URL url = new URL(imageUrl2);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            return BitmapFactory.decodeStream(input);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public void saveBitmapToAndroidData(Bitmap bitmap, File file) {
    if (bitmap != null) {
    try (FileOutputStream out = new FileOutputStream(file)) {
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.flush();
        Log.d("SaveImage", "Image saved in: " + file.getAbsolutePath());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}
}